#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@File Name  : common.py
@Author     : LeeCQ
@Date-Time  : 2020/8/29 11:33
"""
from selenium.webdriver.remote.webdriver import WebDriver as BaseWebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.action_chains import ActionChains
from exc import ElementNotFind, NotLoginError
from chromeBrowser import chrome

import logging
import sys

logger = logging.getLogger("logger")  # 创建实例
formatter = logging.Formatter("[%(asctime)s] < %(funcName)s: %(thread)d > [%(levelname)s] %(message)s")
# 终端日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)  # 日志格式
logger.setLevel(logging.DEBUG)  # 设置日志文件等级


def is_login(_driver: BaseWebDriver):
    """判断是否登录"""
    try:
        _driver.find_element_by_id('topnav')
        return True
    except ElementNotFind:
        return False


def open_tag(_d: BaseWebDriver, nav, sub_nav):
    """打开一个标签页"""
    if is_login(_d) is False:
        raise NotLoginError('检查登录状态')

    def main(__d):
        for __n in __d.find_elements_by_css_selector('#nav > li'):
            if __n.find_element_by_css_selector('a > div.main-nav-text').text == nav:
                ActionChains(_d).move_to_element(__n)
                print(__n.find_element_by_css_selector('a > div.main-nav-text').text)
                return __n.find_elements_by_css_selector('div > ul > li')

    sub_nav_tags = main(_d)
    if sub_nav_tags:
        for _sn in sub_nav_tags:
            print(_sn.find_element_by_xpath('//a').text)
            if _sn.find_element_by_css_selector('a').text == sub_nav:
                print(_sn.find_element_by_css_selector('a').text)
            return _sn.click()
        raise ElementNotFind()
    else:
        raise ElementNotFind()


def add_attribute(_driver: BaseWebDriver, element_obj, attribute_name, value):
    '''
    封装向页面标签添加新属性的方法
    调用JS给页面标签添加新属性，arguments[0]~arguments[2]分别
    会用后面的element，attributeName和value参数进行替换
    添加新属性的JS代码语法为：element.attributeName=value
    比如input.name='test'
    '''
    _driver.execute_script("arguments[0].%s=arguments[1]" % attribute_name, element_obj, value)


def set_attribute(driver, element_obj, attribute_name, value):
    '''
    封装设置页面对象的属性值的方法
    调用JS代码修改页面元素的属性值，arguments[0]~arguments[1]分别
    会用后面的element，attributeName和value参数进行替换
    '''
    driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])", element_obj, attribute_name, value)


__all__ = ['BaseWebDriver', 'home', 'WebElement', 'chrome', 'logger', 'console_handler',
           'is_login', 'open_tag',
           ]

home = 'http://tms.local:8080/'

if __name__ == '__main__':
    from login import login_default
    import time

    open_tag(login_default(), '基础数据', '客户档案')
    time.sleep(5)
